<template>
    <div id="login">
        <h1>注册</h1>
      <van-form @submit="onSubmit">
    <van-field
      v-model="formData.phone"
      placeholder="输入手机号"
      :rules="[{ required: true,  pattern:/^1[3-9]\d{9}$/,message: '请填写正确的手机号' }]"
    />
    <van-field
      v-model="formData.pass"
      type="password"
      placeholder="输入密码"
      :rules="[{pattern:/^\d{4}$/, required: true, message: '请填写密码' }]"
    />
    <van-field
      v-model="formData.password2"
      type="password"
      placeholder="输入确认密码"
      :rules="[{validator, required: true, message: '两次密码输入错误' }]"
    />
    <div style="margin: 16px;">
      <van-button round block type="info" native-type="submit">提交</van-button>
    </div>
  </van-form>
    </div>
  </template>
  
  <script>
  import { user_register} from '@/utils/api';
  import { Toast } from 'vant';
  export default {
    data() {
      return {
          formData:{
              phone: '',
              pass: '',
              password2:'',
          },
      };
    },
    methods: {
        validator(val){
            return val==this.formData.pass?true:false;
        },
      onSubmit() {

          user_register( this.formData ).then((res)=>{
          if( res.data.code == 200 ){
            localStorage.setItem('token',res.data.token);
            localStorage.setItem('userinfo', JSON.stringify( res.data.userinfo ) );
            this.$router.push('/');
            Toast.success('注册成功!')
          }else{
            Toast.fail(res.data.msg)
          }
        })
      },
    },
  };
  </script>
  
  <style>
  #login{
    margin: 50px 20px;
  }
  #login h1{
    font-weight: bold;
    text-align: center;
    line-height: 40px;
    margin-bottom: 50px;
  }
  #login .van-field{
    margin: 20px 0;
  }
  #login .van-field input{
    height: 40px;
    border: 1px solid #ccc;
    border-radius: 20px;
    padding-left: 20px;
    box-sizing: border-box;
    outline: none;
    width: 100%;
  }
  </style>